# coding:utf-8
import requests
import time

"""此方法是转为爬取来自新浪财经的数据而设计的"""


def get_day_data_from_sina(Symbol='usdcad'):
    "爬取外汇数据 日线"
    # 开盘    最低    最高    收盘
    cut = 500  # 最近500天的数据
    url = 'https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_fx_s' + Symbol + '2020_2_1=/NewForexService.getDayKLine?symbol=fx_s' + Symbol + '&_=2020_2_1'
    # url = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_DINIW2019_9_25=/NewForexService.getDayKLine?symbol=DINIW&_=2019_9_25"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}

    response = requests.get(url=url, headers=headers)

    newString = ''

    for i in response.text:
        if i in '0123456789,.-|':
            newString += i
    newString = '[["' + newString.replace(',', '","').replace('","|', '"],["') + '"]]'
    newString = eval(newString)

    data = []
    for i in newString[cut * -1:]:
        data.append([i[0], float(i[1]), float(i[2]), float(i[3]), float(i[4])])

    # print(newString)

    return data


def get_min_data_from_sina(Symbol='usdcad'):
    "爬取外汇数据 日线"
    # 开盘    最低    最高    收盘
    url_harf = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_fx_s" + Symbol + "_1_1580278725141=/NewForexService.getMinKline?symbol=fx_s" + Symbol + "&scale=1&datalen=1440"
    # url =    "https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_GC2020_2_14=/GlobalFuturesService.getGlobalFuturesDailyKLine?symbol=GC&_=2020_2_14&source=web"
    # url = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_fx_seurusd_1_1580278725141=/NewForexService.getMinKline?symbol=fx_seurusd&scale=1&datalen=1440"
    url = url_harf
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
    }

    response = requests.get(url=url, headers=headers)
    print(response.text, 'is get_min_data_from_sina')

    for i, j in zip(response.text.replace('"', ""), range(90000)):
        if i == "(":
            text = response.text[j + 1:-1].replace("d", '"d"').replace("o", '"o"').replace("l", '"l"').replace("h",
                                                                                                               '"h"').replace(
                "c", '"c"').replace("p", '"p"')
            break
    text = eval(text)

    # 把数据反过来
    # text_ = []
    # for i in range(len(text)):
    #     text_.insert(0, text[len(text) - i - 1])
    # text = text_

    data = []
    for i in text:
        data.append([i['d'], float(i['o']), float(i['l']), float(i['h']), float(i['c'])])
    # print(a)
    # del response
    return data

    # return text


def get_all_Symbol(Symbol=None):
    """获取所有的货币对"""
    all = [
        "audcad", "audchf", "audjpy", "audnzd", "audusd",
        "cadchf", "cadjpy",
        "chfjpy",
        "euraud", "eurcad", "eurchf", "eurgbp", "eurjpy", "eurusd",
        "gbpaud", "gbpchf", "gbpjpy", "gbpcad", "gbpnzd", "gbpusd",
        "nzdcad", "nzdchf", "nzdjpy", "nzdusd",
        "usdcad", "usdchf", "usdjpy",
    ]
    if Symbol:
        return [i for i in all if Symbol in i]
    else:
        return all


def get_hour_data_from_sina(Symbol='usdcad'):
    "爬取外汇数据 日线"
    # 开盘    最低    最高    收盘
    cut = 500  # 最近500天的数据
    # https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_fx_seurusd_60_1581058843914=/NewForexService.getMinKline?symbol=fx_seurusd&scale=60&datalen=120
    url = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_fx_s" + Symbol + "_60_1581058843914=/NewForexService.getMinKline?symbol=fx_s" + Symbol + "&scale=60&datalen=120"
    # 'https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_fx_s' + Symbol + '2020_2_1=/NewForexService.getDayKLine?symbol=fx_s' + Symbol + '&_=2020_2_1'
    # url = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_DINIW2019_9_25=/NewForexService.getDayKLine?symbol=DINIW&_=2019_9_25"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}

    response = requests.get(url=url, headers=headers)

    newString = ''

    for i in response.text:
        if i in '0123456789,.-|':
            newString += i
    newString = '[["' + newString.replace(',', '","').replace('","|', '"],["') + '"]]'
    newString = eval(newString)

    data = []
    for i in newString[cut * -1:]:
        data.append([i[0], float(i[1]), float(i[2]), float(i[3]), float(i[4])])

    # print(newString)
    return response.text

    return data


def get_GOLD_day_data_from_sina():
    # 纽约金 CFD
    url = 'https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_GC2020_2_14=/GlobalFuturesService.getGlobalFuturesDailyKLine?symbol=GC&_=2020_2_14&source=web'
    # url = url_harf
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
    }

    response = requests.get(url=url, headers=headers)
    # print(response.text, 'is get_GOLD_day_data_from_sina')

    for i, j in zip(response.text, range(10000)):
        if i == '[':
            # s=j
            text = response.text[j:-2]
            break
        # elif i==']':
        #     text=response.text[s:j]
        #     break
    # print(eval(text))
    return eval(text)


def GOLD_():
    """获取纽约金CFD时价"""

    # 纽约金
    url = "https://hq.sinajs.cn/?_=0.7089865065563885&list=hf_GC"

    # 伦敦金
    url = "https://hq.sinajs.cn/?_=0.7829746211417856&list=hf_XAU"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
    }

    response = requests.get(url=url, headers=headers)
    # print(response.text)
    prince = ''
    for i in response.text:
        if i == ',':
            break
        elif i in "1234567890.":
            prince += i
    return float(prince)


def 沪金():
    """获取期货信息"""
    url = "https://hq.sinajs.cn/?_=1581730950041/&list=nf_AU2008,nf_AU2004,nf_AU2010,nf_AU2012,nf_AU1910,nf_AU2001"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
    }

    response = requests.get(url=url, headers=headers)

    print(response.text)

    return


if __name__ == '__main__':
    # 日期  开盘    最低    最高    收盘
    # a = get_day_data_from_sina()
    # a = get_min_data_from_sina()
    # print(a)
    # while 1:
    #     a = get_hour_data_from_sina('usdcad')
    #     print(a)
    #     # del a
    #     time.sleep(4)
    # a = get_GOLD_day_data_from_sina()
    # print(a)
    # a = 沪金()
    # print(a)
    GOLD_()